from flask_sqlalchemy import SQLAlchemy, declarative_base
from flask_jsontools import JsonSerializableBase

from flask_migrate import Migrate

db = SQLAlchemy()
migrate = Migrate()

Base = declarative_base(cls=(JsonSerializableBase))
# Base = db.Model
# db.make_declarative_base(declarative_base(cls=(JsonSerializableBase, db.Model)))
class User(db.Model, Base):
    __tablename__='tb_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    account = db.Column(db.String(20), nullable=False)
    alias = db.Column(db.String(20), nullable=False)
    password = db.Column('pass_word', db.String(255), nullable=False)
    mobile = db.Column(db.String(20), nullable=False)

class Task(db.Model, Base):
    __tablename__='tb_task'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    taskName = db.Column('task_name', db.String(255), nullable=False)
    allinCost = db.Column('all_in_cost', db.Float(precision=2), nullable=False)
    deadline = db.Column(db.DateTime, nullable=False)
    createdBy = db.Column('create_by', db.ForeignKey('tb_user.id'), nullable=True)
    createdTime = db.Column('created_time', db.DateTime, default='CURRENT_TIMESTAMP')
    owner = db.relationship('User', backref=db.backref('tasks', lazy=False))

class Cost(db.Model, Base):
    __tablename__='tb_cost'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    taskId = db.Column('task_id', db.ForeignKey('tb_task.id'), nullable=False)
    cost = db.Column(db.Float(precision=2), nullable=False)
    createdBy = db.Column('created_by', db.ForeignKey('tb_user.id'), nullable=False)
    createdTime = db.Column('created_time', db.DateTime, default='CURRENT_TIMESTAMP', nullable=False)
    task = db.relationship('Task', backref=db.backref('costs', lazy='dynamic'))


def init_app(app):
    db.init_app(app)
    migrate.init_app(app, db)
